package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_Type_KEY;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lwk
 * @since 2025-6-1
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        //1.从redis中查询商铺类型
        String shopTpyeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_Type_KEY);
        //2. 判断是否存在
         if (StrUtil.isNotBlank(shopTpyeJson)) {
             //3.存在直接返回
              List<ShopType> shopTypeList = JSONUtil.toList(shopTpyeJson, ShopType.class);
               return Result.ok(shopTypeList);
         }
        //4.不存在，查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        //5.数据库中不存在，返回错误
        if (typeList.isEmpty()) {
             return Result.fail("店铺不存在");
        }
        //6. 存在，写入redis（用String类型来存）
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_Type_KEY, JSONUtil.toJsonStr(typeList), 36000L, TimeUnit.MINUTES);
        //7.返回集合
         return Result.ok(typeList);

    }
}
